package com.yc.testupload.publisher;

import com.yc.testupload.controller.DocumentsServlet;
import com.yc.testupload.model.Account;
import com.yc.testupload.model.PublishResult;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 微信平台发布器
 * 实现微信平台的内容发布功能
 */
public class WechatPublisher implements PlatformPublisher {
    private static final Logger logger = LogManager.getLogger(WechatPublisher.class);
    private static final String PLATFORM_TYPE = "wechat";
    private DocumentsServlet documentsServlet;

    /**
     * 设置DocumentsServlet实例
     */
    public void setDocumentsServlet(DocumentsServlet documentsServlet) {
        this.documentsServlet = documentsServlet;
    }

    @Override
    public PublishResult publish(Account account, Map<String, Object> content) {
        logger.info("开始发布到微信平台，账号: {}", account.getAccountName());

        try {
            // 检查DocumentsServlet是否已设置
            if (documentsServlet == null) {
                throw new IllegalStateException("DocumentsServlet未初始化");
            }

            // 从content中获取文章信息
            String articleTitle = content.getOrDefault("title", "").toString();
            String articleContent = content.getOrDefault("content", "").toString();
            logger.info("微信发布内容 - 标题: {}, 账号ID: {}", articleTitle, account.getAccountId());

            // 构建文档JSON对象
            JSONObject documentObj = new JSONObject();
            documentObj.put("title", articleTitle);
            documentObj.put("content", articleContent);
            
            // 将文档添加到数组中
            JSONArray documentsArray = new JSONArray();
            documentsArray.put(documentObj);
            
            // 准备公众号账号ID列表
            List<String> accountIds = new ArrayList<>();
            accountIds.add(account.getAccountId());
            
            // 调用DocumentsServlet的批量发布方法
            logger.info("调用DocumentsServlet的batchPublishToMultipleWechatAccounts方法发布到微信公众号草稿箱");
            Map<String, Object> result = documentsServlet.batchPublishToMultipleWechatAccounts(null, documentsArray, accountIds);
            
            // 解析发布结果
            Map<String, Object> accountResults = (Map<String, Object>) result.get("accountResults");
            Map<String, Object> specificAccountResult = (Map<String, Object>) accountResults.get(account.getAccountId());
            
            boolean success = false;
            String message = "微信平台发布失败";
            
            if (specificAccountResult != null) {
                int successCount = ((Number) specificAccountResult.get("successCount")).intValue();
                success = successCount > 0;
                message = (String) specificAccountResult.getOrDefault("message", success ? "微信平台发布成功" : "微信平台发布失败");
            }
            
            PublishResult publishResult = new PublishResult(success, message);
            publishResult.setPlatformResponse("微信平台返回: " + result.toString());
            logger.info("微信平台发布完成，账号: {}, 结果: {}", account.getAccountName(), success ? "成功" : "失败");
            
            return publishResult;
        } catch (Exception e) {
            logger.error("微信平台发布失败: {}", e.getMessage(), e);
            PublishResult result = new PublishResult(false, "微信平台发布失败: " + e.getMessage());
            return result;
        }
    }

    @Override
    public String getPlatformType() {
        return PLATFORM_TYPE;
    }
}